/* $RCSFile: EnhancedHtmlEdit.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/EnhancedHTML/EnhancedHtmlEdit.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:53  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Core;
using AddonNice.Configuration;
using AddonNice.UI;
using AddonNice.Security;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Settings.PageModules.EnhancedHtml;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.EnhancedHtml
{
	/// <summary>
	/// AddonNice EnhancedHtml Module EditItemPage
	/// </summary>
	public partial class EnhancedHtmlEdit : AddonNice.UI.EditItemPage
	{
		private readonly string tokenModule         = "#MODULE#";
		private readonly string tokenPortalModule   = "#PORTALMODULE#";

		ImageButton cmdNewPage;
		ImageButton cmdEditPage;
		ImageButton cmdDeletePage;
		ImageButton cmdReturn;
		ImageButton cmdPageUpdate;
		ImageButton cmdPageCancel;



		protected AddonNice.UI.WebControls.IHtmlEditor DesktopText;
		EnhancedHtmlDB ehdb			=	new EnhancedHtmlDB();
		ModulesDB mdb				=	new ModulesDB();


		void BindListAllModules()
		{
			try
			{
				DataTable tb1					= mdb.GetModulesAllPortals();
				listAllModules.DataSource		= tb1;
				listAllModules.DataValueField	= "ModuleID";
				listAllModules.DataTextField	= "ModuleTitle";
				listAllModules.DataBind();
			}
			catch (Exception ex1)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedHtmlEdit Page_Load listAllModules ex: {0}", ex1),PageTraceSwitch.Sw.Info);
                throw;
			}
		}

		void BindListModules()
		{
			try
			{
				DataTable tb				= mdb.GetModulesSinglePortal(portalSettings.PortalID);
				listModules.DataSource		= tb;
				listModules.DataValueField	= "ModuleID";
				listModules.DataTextField	= "ModTitle";
				listModules.DataBind();
			}
			catch (Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedHtmlEdit Page_Load listModules ex: {0}", ex),PageTraceSwitch.Sw.Info);
                throw;
			}
		}

		/// <summary>
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        protected void Page_Load(object sender, System.EventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit Page_Load IsPostBack: {0},ModuleID: {1}", IsPostBack,ModuleID),PageTraceSwitch.Sw.Info);
			DesktopText					    =   GetEditor(PlaceHolderHTMLEditor);

			if (!Page.IsPostBack) 
			{
				if ( moduleSettingsDic[EStr.ENHANCEDHTML_GET_CONTENTS_FROM_PORTALS].ToBool() )
				{
					kindOfContent.Items.Add(new ListItem("External Module", "Portal"));
					BindListAllModules();
				}
				BindListModules();

				string command			    =   LocalizeHelper.Localize(EStr.ENHANCEDHTML_CONFIRMDELETEMESSAGE, "Are you sure you need to delete this item ?");
				string title			    =   LocalizeHelper.Localize("DELETE", "Delete Item");
                setClientConfirmAttributes(cmdDeletePage,command,title);
                ViewState["UrlReferrer"]    =   HttpUrlBuilder.BuildUrl(PageID);

				CultureInfo[] cultureList   =   AddonNice.UI.WebControls.PortalModuleControl.GetLanguageList(true);

				lstLanguages.Items.Add (new ListItem(LocalizeHelper.Localize(EStr.ENHANCEDHTML_SHOWALLPAGES, "All Pages"), "0"));
				foreach (CultureInfo ci in cultureList)
				{
					lstLanguages.Items.Add (new ListItem(ci.DisplayName, (ci.LCID).ToString()));
					listLanguages.Items.Add(new ListItem(ci.DisplayName, (ci.LCID).ToString()));
				}
				lstLanguages.SelectedIndex  =   0;
				listLanguages.SelectedIndex =   0;
				buildList ();
			}
       }

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al            =   new ArrayList();
				al.Add ("875254B7-2471-491f-BAF8-4AFC261CC224");
				return al;
			}
		}

		private void buildList ()
		{
			bool showAllPages			=	(int.Parse(lstLanguages.SelectedItem.Value) < 1) ;
			CultureInfo[] cultureList	=	AddonNice.UI.WebControls.PortalModuleControl.GetLanguageList(true);
			SqlDataReader dr			=	null;
			lstPages.Items.Clear();
			try
			{
				if (showAllPages)
				{
					dr = ehdb.GetAllPages(ModuleID);
				} 
				else 
				{
					dr = ehdb.GetLocalizedPages (ModuleID, int.Parse(lstLanguages.SelectedItem.Value));
				}
				while ( dr.Read())
				{
					if (showAllPages)
					{
						int ccode			= (int)dr["CultureCode"];
						string strTxt		= string.Empty;

						foreach (CultureInfo ci in cultureList)
						{
							if (ccode == ci.LCID) 
									strTxt	= ci.DisplayName;
						}
						if (strTxt != string.Empty) 
						{
							lstPages.Items.Add(new ListItem ((string) dr["Title"]+ " (" + strTxt + ")", dr["ItemID"].ToString()));
						}
					}
					else 
					{
						lstPages.Items.Add(new ListItem ((string) dr["Title"], dr["ItemID"].ToString()));
					}
				}
			}
			catch (Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedHtmlEdit buildAll ex: {0}", ex),PageTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( dr != null )
					dr.Close();	
			}
			if (lstPages.Items.Count > 0)
			{
				lstPages.SelectedIndex		= 0;
				cmdEditPage.Enabled			= true;
				cmdDeletePage.Enabled		= true;
			} 
			else 
			{
				cmdEditPage.Enabled			= false;
				cmdDeletePage.Enabled		= false;
			}
		}


		#region Web Form Designer generated code

		
		protected override void OnPreInit(EventArgs e)
        {
			// it is impossible to have dynamic SkinIDs with buttons placed in the aspx page
			// it is also impossible to simply add skinids to buttons declared in the aspx page in OnPreinit, they are not created
			//so we need to create them here and add them to a placeholder in OnInit
			string strLoc	                =	LocalizeHelper.GetCurrentNeutralCultureName();
			cmdNewPage						=	new ImageButton();
			cmdNewPage.SkinID				=	"AddPage";
			cmdNewPage.AlternateText		=	LocalizeHelper.Localize(EStr.ENHANCEDHTML_NEWPAGE,"New Page");
			cmdNewPage.CausesValidation		=	false;
			
			cmdEditPage						=	new ImageButton();
			cmdEditPage.SkinID				=	"EditBtn";
			cmdEditPage.AlternateText		=	LocalizeHelper.Localize(EStr.ENHANCEDHTML_EDITPAGE,"Edit");
			cmdEditPage.CausesValidation	=	false;
			cmdEditPage.Enabled				=	false;
			
			cmdDeletePage					=	new ImageButton();
			cmdDeletePage.SkinID			=	"DeleteBtn";
			cmdDeletePage.AlternateText		=	LocalizeHelper.Localize(EStr.ENHANCEDHTML_DELETEPAGE,"Delete");
			cmdDeletePage.CausesValidation	=	false;
			cmdDeletePage.Enabled			=	false;
			cmdReturn						=	new ImageButton();
			cmdReturn.SkinID				=	"ReturnBtn";
			cmdReturn.AlternateText			=	LocalizeHelper.Localize(EStr.ENHANCEDHTML_RETURN,"return");
			cmdReturn.CausesValidation		=	false;

			cmdPageUpdate					=	new ImageButton();
			cmdPageUpdate.SkinID			=	"Update_"+strLoc;
			cmdPageUpdate.AlternateText		=	LocalizeHelper.Localize(EStr.ENHANCEDHTML_UPDATE,"Update");
			cmdPageUpdate.CausesValidation	=	false;
			cmdPageCancel					=	new ImageButton();
			cmdPageCancel.SkinID			=	"Cancel_"+strLoc;
			cmdPageCancel.AlternateText		=	LocalizeHelper.Localize(EStr.ENHANCEDHTML_CANCEL,"Cancel");
			cmdPageCancel.CausesValidation	=	false;

			base.OnPreInit(e);
        }
		
		protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent() 
        {    
			lstLanguages.SelectedIndexChanged	+=	new EventHandler(this.selectLocalizedPages);
			kindOfContent.SelectedIndexChanged  +=	new EventHandler(this.kindOfContents_Click);
			listModules.SelectedIndexChanged	+=	new EventHandler(this.kindOfContents_Click);
			
			// insert buttons in palceholder, skinids has been set
			Btn1PlaceHolder.Controls.Add(cmdNewPage);
			Btn1PlaceHolder.Controls.Add(new LiteralControl("&#160;"));
			Btn1PlaceHolder.Controls.Add(cmdDeletePage);
			Btn1PlaceHolder.Controls.Add(new LiteralControl("&#160;"));
			Btn1PlaceHolder.Controls.Add(cmdEditPage);
			Btn1PlaceHolder.Controls.Add(new LiteralControl("&#160;"));
			Btn1PlaceHolder.Controls.Add(cmdReturn);

			Btn2PlaceHolder.Controls.Add(cmdPageUpdate);
			Btn2PlaceHolder.Controls.Add(new LiteralControl("&#160;"));
			Btn2PlaceHolder.Controls.Add(cmdPageCancel);
		
			cmdNewPage.Click					+=	new ImageClickEventHandler(cmdNewPage_Click);
			cmdEditPage.Click					+=	new ImageClickEventHandler(cmdEditPage_Click);
			cmdDeletePage.Click				    +=	new ImageClickEventHandler(cmdDeletePage_Click);
			cmdReturn.Click					    +=	new ImageClickEventHandler(cmdReturn_Click);
			cmdPageUpdate.Click				    +=	new ImageClickEventHandler(cmdPageUpdate_Click);
			cmdPageCancel.Click				    +=	new ImageClickEventHandler(cmdPageCancel_Click); 
			Load								+=	new EventHandler(Page_Load);
		}

		#endregion

		#region Events
		
		void cmdReturn_Click(object sender, ImageClickEventArgs e)
		{
			Response.Redirect(((string) ViewState["UrlReferrer"]), true);
		}

		void cmdPageCancel_Click(object sender, ImageClickEventArgs e)
		{
			pnlSelectPage.Visible = true;
			pnlEditPage.Visible = false;
			if (lstPages.SelectedItem == null) // Cancel a new page
			{
				if (lstPages.Items.Count > 0)
				{
					lstPages.SelectedIndex  = 0;
					cmdEditPage.Enabled     = true;
					cmdDeletePage.Enabled   = true;
				} 
				else 
				{
					lstPages.SelectedIndex  = -1;
					cmdEditPage.Enabled     = false;
					cmdDeletePage.Enabled   = false;
				}
			}
		}

		void cmdDeletePage_Click(object sender, ImageClickEventArgs e)
		{
			if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( "[V]EnhancedHtmlEdit cmdDeletePage_Click BEG",PageTraceSwitch.Sw.Info);
			if ((lstPages.SelectedItem.Value != null) && (lstPages.SelectedItem.Value != "-1"))
			{
				ehdb.DeletePage(int.Parse(this.lstPages.SelectedItem.Value));
				if (lstPages.Items.Count > 0)
				{
					lstPages.SelectedIndex	= 0;
					cmdEditPage.Enabled		= true;
					cmdDeletePage.Enabled	= true;
				} 
				else 
				{
					lstPages.SelectedIndex	= -1;
					cmdEditPage.Enabled		= false;
					cmdDeletePage.Enabled	= false;
				}
				Response.Redirect(Request.Url.ToString(), true);
			}
		}

		void cmdEditPage_Click(object sender, ImageClickEventArgs e)
		{
			if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( "[V]EnhancedHtmlEdit cmdEditPage_Click BEG",PageTraceSwitch.Sw.Info);
			pnlSelectPage.Visible					= false;
			pnlEditPage.Visible						= true;
			txtPageName.Text						= string.Empty;
			txtViewOrder.Text						= "100";

			SqlDataReader dr						= null;
			try
			{
				dr									= ehdb.GetSinglePage(int.Parse(lstPages.SelectedItem.Value));
				if (dr.Read())
				{
					txtPageName.Text		    =	(string)dr["Title"];
					txtViewOrder.Text		    =	dr["ViewOrder"].ToString();
					string strCult			    =	dr["CultureCode"].ToString();
					foreach (ListItem li in listLanguages.Items) 
					{
						li.Selected			    =   li.Value.Equals(strCult);
					}
					DesktopText.TextContent		=   Server.HtmlDecode(((string) dr["DesktopHtml"]));
					CreatedBy.Text			    =   (string) dr["CreatedByUser"];
					CreatedDate.Text		    =   ((DateTime) dr["CreatedDate"]).ToShortDateString();
				}
			}
			catch (Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedHtmlEdit cmdEditPage_Click ex: {0}", ex),PageTraceSwitch.Sw.Info);
				throw;
			}
			finally
			{
				if ( dr != null )
					dr.Close();
			}
		
			if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdEditPage_Click DesktopText.Text: {0}", DesktopText.TextContent),PageTraceSwitch.Sw.Info);
            string txtContent   =   DesktopText.TextContent;
			if (txtContent.StartsWith(tokenModule)) 
			{
				kindOfContent.SelectedIndex		=	1;
			}
			else if (txtContent.StartsWith(tokenPortalModule)) 
			{
				kindOfContent.SelectedIndex		=	2;
			}
			else kindOfContent.SelectedIndex = 0;
			kindOfContents_Click (sender, e);
		}

		void cmdNewPage_Click(object sender, ImageClickEventArgs e)
		{
			if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( "[V]EnhancedHtmlEdit cmdNewPage_Click BEG",PageTraceSwitch.Sw.Info);
			pnlSelectPage.Visible	    = false;
			pnlEditPage.Visible		    = true;
			txtPageName.Text		    = string.Empty;
			txtViewOrder.Text	        = "100";
			DesktopText.TextContent	    = string.Empty;
			lstPages.SelectedIndex	    = -1;
		}

		void cmdPageUpdate_Click(object sender, ImageClickEventArgs e)
		{
			if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( "[V]EnhancedHtmlEdit cmdPageUpdate_Click BEG",PageTraceSwitch.Sw.Info);
            string titlePage		= txtPageName.Text.Trim();
			if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdPageUpdate_Click titlePage: {0}", titlePage),PageTraceSwitch.Sw.Info);
			if ( string.IsNullOrEmpty(titlePage) )
			{
				titlePage			=	"Page";
			}
			string orderView		= txtViewOrder.Text.Trim();
			if ( string.IsNullOrEmpty(orderView) )
			{
				orderView			=	"100";
			}
			int order				= 0;
			try 
			{
				order				= int.Parse(orderView);
			}
			catch 
			{
			}
			if (order < 1) 
			{
				orderView			= "100";
				txtViewOrder.Text	= orderView;
				order				= 100;
			}

			string text = string.Empty;
			int i;

			if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdPageUpdate_Click kindOfContent.SelectedValue: {0}", kindOfContent.SelectedValue),PageTraceSwitch.Sw.Info);
			switch (kindOfContent.SelectedValue) 
			{
				case "Editor":
					text = Server.HtmlEncode(DesktopText.TextContent);
			        if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdPageUpdate_Click text: {0}", text ),PageTraceSwitch.Sw.Info);
					if (text.StartsWith(tokenModule) || text.StartsWith(tokenPortalModule))
						text = string.Empty;
					break;
				case "Module":
					i = int.Parse(listModules.SelectedValue);
					if (i == 0 || i == this.ModuleID) return; // Cannot select this module
					text = tokenModule + listModules.SelectedValue;
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdPageUpdate_Click Module Selected text: {0}", text),PageTraceSwitch.Sw.Info);
					break;
				case "Portal":
					i = int.Parse(listAllModules.SelectedValue);
					if (i == 0 || i == this.ModuleID) return; // Cannot select this module
					text = tokenPortalModule + listAllModules.SelectedValue;
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdPageUpdate_Click PortalModule Selected text: {0}", text),PageTraceSwitch.Sw.Info);
					break;
			}

			string user = PortalSecurity.Wrapper.userName;
            if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdPageUpdate_Click user: {0}", user ),PageTraceSwitch.Sw.Info);
			try
			{
				int langId	=	int.Parse(listLanguages.SelectedItem.Value);
				if (lstPages.SelectedIndex >= 0)
				{
					int pgItemID = int.Parse(lstPages.SelectedItem.Value);
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit cmdPageUpdate_Click pgItemID: {0}", pgItemID),PageTraceSwitch.Sw.Info);
					ehdb.UpdatePage(ModuleID, pgItemID, user, titlePage, order, langId, text);
				}
				else
				{
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( "[V]EnhancedHtmlEdit cmdPageUpdate_Click pgItemID newPage",PageTraceSwitch.Sw.Info);
					ehdb.AddPage(ModuleID,user, titlePage, order, langId, text);
				}
			}
			catch (Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedHtmlEdit cmdPageUpdate_Click ex: {0}", ex),PageTraceSwitch.Sw.Info);
				throw;
			}
			pnlSelectPage.Visible = true;
			pnlEditPage.Visible = false;
			buildList();
		}

		protected void selectLocalizedPages(object sender, System.EventArgs e)
		{
			buildList();
		}

		private void kindOfContents_Click(object sender, EventArgs e)
		{
            if (PageTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit kindOfContents_Click kindOfContent.SelectedValue: {0}", kindOfContent.SelectedValue ),PageTraceSwitch.Sw.Info);
			switch (kindOfContent.SelectedValue)
			{
				case "Editor":
					Literal2.Text = LocalizeHelper.Localize(EStr.HTML_DESKTOP_CONTENT,"Desktop HTML Content");
					PlaceHolderHTMLEditor.Visible   = true;
					listModules.Visible             = false;
					listAllModules.Visible          = false;
					string text = Server.HtmlEncode(DesktopText.TextContent);
					if (text.StartsWith(tokenModule) || text.StartsWith(tokenPortalModule))
						DesktopText.TextContent     = string.Empty;
                    if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedHtmlEdit kindOfContents_Click kindOfContent.SelectedValue: {0}", kindOfContent.SelectedValue ),PageTraceSwitch.Sw.Info);
					break;
				case "Module":
					Literal2.Text = LocalizeHelper.Localize(EStr.ENHANCEDHTML_SELECT_MODULE,"Select a module from this portal for show the contents in this page");
					PlaceHolderHTMLEditor.Visible   = false;
					listModules.Visible             = true;
					listAllModules.Visible          = false;
					BindListModules();
					if (DesktopText.TextContent.StartsWith(tokenModule)) 
					{
						int module						=	int.Parse(DesktopText.TextContent.Substring(tokenModule.Length));
						foreach (ListItem li in listModules.Items)
							if (int.Parse(li.Value) == module) 
								li.Selected				=	true;
					}
					break;
				case "Portal":
					Literal2.Text                   = LocalizeHelper.Localize(EStr.ENHANCEDHTML_SELECT_MODULE_PORTAL,"Select a module in database portals for show the contents in this page");
					PlaceHolderHTMLEditor.Visible   = false;
					listModules.Visible             = false;
					listAllModules.Visible          = true;
					BindListAllModules();
					if (DesktopText.TextContent.StartsWith(tokenPortalModule)) 
					{
						int module						=	int.Parse(DesktopText.TextContent.Substring(tokenPortalModule.Length));
						foreach (ListItem li in listAllModules.Items)
							if (int.Parse(li.Value) == module) 
								li.Selected				=	true;
					}
					break;
			}
		}
		#endregion
    }
}

